//
//
// 家庭成员位置变化处理

package member

import (
	"adai.design/jarvis/common/log"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"time"
)

type httpPackageInfo struct {
	Member  string   `json:"membership"`
	Home    string   `json:"home,omitempty"`
	Session string   `json:"session,omitempty"`
	DevType string   `json:"dev_t,omitempty"`
	State   string   `json:"state,omitempty"`
	Msg     *Message `json:"message,omitempty"`
}

// 处理家庭成员位置变化
func serveHTTP(response http.ResponseWriter, request *http.Request) {
	log.Info("mark")
	buf, err := ioutil.ReadAll(request.Body)
	if err != nil {
		return
	}
	log.Info("mark")
	log.Info("member-http-server: %s", string(buf))

	var req httpPackageInfo
	err = json.Unmarshal(buf, &req)
	if err != nil {
		http.Error(response, "request-message-format-invalid", 404)
		return
	}

	_, _, err = accounts.SessionCheck(req.Member, req.Session, req.DevType)
	if err != nil {
		rsp := &httpPackageInfo{
			Member: req.Member,
			Home:   req.Home,
			State:  err.Error(),
		}
		buf, _ = json.Marshal(rsp)
		log.Info("data: %s", string(buf))
		_, _ = response.Write(buf)
		return
	}

	result := make(chan *MessagePkg, 1)
	defer close(result)

	pkg := &MessagePkg{
		Type: PkgTypeChanel,
		Ctx: &Context{
			HomeId:   req.Home,
			MemberId: req.Member,
			Session:  req.Session,
			Result:   result,
		},
		Msg: req.Msg,
	}
	workers.rpkg <- pkg

	select {
	case ack, ok := <-result:
		if ok {
			log.Debug("post ack: %s", ack.String())
			rsp := &httpPackageInfo{
				Member: req.Member,
				Home:   req.Home,
				State:  "ok",
				Msg:    ack.Msg,
			}
			buf, _ = json.Marshal(rsp)
			log.Info("data: %s", string(buf))
			_, _ = response.Write(buf)
			return
		}

	case <-time.After(time.Second * 3):
		rsp := &httpPackageInfo{
			Member: req.Member,
			Home:   req.Home,
			State:  "timeout",
		}
		buf, _ = json.Marshal(rsp)
		log.Info("data: %s", string(buf))
		_, _ = response.Write(buf)
		return
	}

}
